<template>
  <div class="view-fill">
    <div v-show="!assetDetailInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :needReturn="!flowFormType"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button
            :disabled="!canSave"
            v-if="
              !id &&
              $permission('financeTypeAdjust:saveAndSubmit') &&
              !flowFormType
            "
            @click="saveAndSubmit()"
            >保存并提交</el-button
          >
          <el-button v-if="!flowFormType" :disabled="!canSave" @click="save()"
            >保存</el-button
          >
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-useDeptId>
                <el-input
                  v-model="formInfo.data.useDeptName"
                  type="input"
                  class="not-mongolia"
                  :disabled="true"
                  placeholder="请选择使用部门"
                >
                  <template #append>
                    <el-icon @click="openUseDeptWindow"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-depotId>
                <el-input
                  v-model="formInfo.data.depotName"
                  type="input"
                  class="not-mongolia"
                  :disabled="true"
                  placeholder="请选择仓库"
                >
                  <template #append>
                    <el-icon @click="openDepotWindow"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addProduct>
                <el-button
                  :disabled="
                    !(formInfo.data.useDeptId > 0 || formInfo.data.depotId > 0)
                  "
                  @click="addProduct"
                  >添加资产</el-button
                >
              </template>

              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除资产</el-button
                >
              </template>
              <template v-slot:filter-productCodeScan>
                <ScanInputBox
                  :disabled="
                    !(formInfo.data.useDeptId || formInfo.data.depotId)
                  "
                  :query="scanInfo.query"
                  :api="scanInfo.api"
                  :is-finance-asset="true"
                  @callback="onCallBackScanData"
                />
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="false"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isDynamic="true"
                  :row-class-name="tableRowClassName"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-assetName="scope">
                    <span
                      class="slip-edit"
                      @click="showAssetDetail(scope.row)"
                      >{{ scope.row.assetName }}</span
                    >
                  </template>
                  <template v-slot:col-adjustAfterValue="scope">
                    <el-form-item
                      style="margintop: 18px"
                      :prop="`data.${scope.$index}.adjustAfter`"
                      :rules="[
                        {
                          required: scope.$index >= 0,
                          message: '请输选择调整值',
                          trigger: 'change',
                        },
                      ]"
                    >
                      <el-input
                        v-model="scope.row.adjustAfterValue"
                        type="input"
                        :disabled="true"
                        class="not-mongolia"
                        placeholder="请选择调整值"
                      >
                        <template #append>
                          <el-icon @click="openFinanceTypeWindow(scope.row)"
                            ><MoreFilled
                          /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :check-box="true"
      :tableKey="'addFinanceAssetByUse-com.slip.spd.entity.vo.core.CoreAssetVO'"
      @callback="callBackAsset"
    />
    <!-- 详情页 -->
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
    <Select-setting-category
      v-if="selectFinanceTypeInfo.visible"
      v-model:showDialog="selectFinanceTypeInfo.visible"
      :saveEmpty="true"
      :check-box="false"
      :query="selectFinanceTypeInfo.query"
      :highlight-row="true"
      @callback="selectFinanceTypeInfoCallBack"
    />
    <select-dept
      v-if="useDeptInfo.visible"
      v-model:show-dialog="useDeptInfo.visible"
      :query="useDeptInfo.query"
      :checked-row-list="useDeptInfo.checkedRowList"
      :check-box="false"
      :highlight-row="true"
      :save-empty="true"
      @callback="selectUseDeptCallback"
    />
    <SelectDepot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectDepotInfo.query"
      :save-empty="true"
      :checked-row-list="selectDepotInfo.checkedRowList"
      @callback="selectDepotCallBack"
    />
  </div>
</template>
<script setup name="financeTypeAdjustModify">
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'
import PageFilter from '@/components/PageFilter/index'
import selectAsset from '@/components/SelectAsset/index'
import ScanInputBox from '@/components/SelectAsset/ScanInputBox'
import SelectSettingCategory from '@/components/SelectSettingCategory/index'
import { getCustomizeSetting } from '@/api/customize'
import {
  adjustFinanceTypeOrderDetailCustomizeListAll,
  getAdjustFinanceTypeById,
  createAdjustFinanceType,
  createAdjustFinanceTypeAndSave,
  updateAdjustFinanceType,
  refushOrderDetail,
  flowSubmitAdjustFinanceTypeOrder,
} from '@/api/asset.js'
import moment from 'moment'
import {
  getCurrentFiscalPeriod,
  assetCardScan,
  getDeptAll,
  getDepotAll,
} from '@/api/core'

const emits = defineEmits()
const { proxy } = getCurrentInstance()
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)

const props = defineProps({
  title: {
    type: String,
    default: '修改财务类别',
  },
  id: {
    type: Number,
  },
  visible: {
    type: Boolean,
    default: false,
  },
  flowFormType: {
    type: String,
    default: '',
  },
})
const useDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
  },
  checkedRowList: [],
})
const selectDepotInfo = ref({
  visible: false,
  checkedRowList: [],
  query: {
    depotAuth: 'id',
    status: 1,
    useTypeId: 2,
    // isCargoSpaceManage: 0,
    idNotIn: '',
  },
})

const scanInfo = reactive({
  api: assetCardScan,
  query: {
    assetStatus: '1,3',
    assetSourceAuth: true,
    financeAssetFlag: true,
  },
})
const formInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      labelTip: '',
      TimePickerOptions: {},
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
    {
      label: '所在位置',
      value: 'position',
      type: 'radio-model',
      code: 'asset_inventory_location',
      event: 'position',
    },
    {
      label: '使用部门',
      value: 'useDeptId',
      type: 'slot',
    },
    {
      label: '仓库',
      value: 'depotId',
      type: 'slot',
      show: false,
    },
  ],
  rules: {
    businessDate: [
      {
        required: true,
        message: '请选择业务日期',
        trigger: 'change',
      },
    ],
    useDeptId: [
      {
        required: true,
        message: '请选择使用部门',
        trigger: 'change',
      },
    ],
    depotId: [
      {
        required: true,
        message: '请选择仓库',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '120px',
})
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
  },
  list: [
    {
      type: 'slot',
      value: 'addProduct',
    },
    {
      type: 'slot',
      value: 'removeProduct',
    },
    {
      type: 'slot',
      value: 'productCodeScan',
    },
  ],
})
const tableInfo = reactive({
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
const selectAssetInfo = reactive({
  visible: false,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      assetSourceAuth: {
        asTbName: 'core_asset,core_asset',
        columnName: 'use_dept_id,depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'assetSourceAuth',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
      assetStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,3',
      },
      isLocked: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      isFinanceAsset: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      depotId: {
        queryType: 'IN',
        value: '',
      },
      useDeptId: {
        queryType: 'IN',
        value: '',
      },
    },
    queryParams: {
      // availableMonth: 'true',
    },
  },
})
const assetDetailInfo = reactive({
  visible: false,
  id: '',
  title: '资产详情',
})
const selectFinanceTypeInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {},
})
const clickRow = ref({})
const formRefs = ref('')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.data.length
})
const canRemoveProduct = computed(() => {
  return tableInfo.selections.length
})

watch(
  () => formInfo.data.position,
  (val) => {
    if (val === 1) {
      showFieldListItem(false, 'depotId')
      showFieldListItem(true, 'useDeptId')
      selectAssetInfo.query.queryMap['depotId'].value = ''
      selectDepotInfo.value.checkedRowList = []
      formInfo.data['depotId'] = -2
      formInfo.data['depotName'] = ''
      scanInfo.query.depotId = ''
      selectAssetInfo.query.queryMap.assetStatus.value = '1'
      scanInfo.query.assetStatus = '1'
    } else if (val === 2) {
      showFieldListItem(true, 'depotId')
      showFieldListItem(false, 'useDeptId')
      selectAssetInfo.query.queryParams['useDeptIdMult'] = ''
      formInfo.data['useDeptId'] = -2
      formInfo.data['useDeptName'] = ''
      useDeptInfo.value.checkedRowList = []
      scanInfo.query.deptId = ''
      selectAssetInfo.query.queryMap.assetStatus.value = '3'
      scanInfo.query.assetStatus = '3'
    }
    tableInfo.data = []
    tableInfo.selections = []
  },
  {
    deep: true,
  }
)

let obj = {
  adjustReason: {
    label: '调整原因',
    value: 'adjustReason',
    componentType: 'input',
    maxlength: 255,
    type: 'input',
    show: false,
    hidden: true,
  },
  adjustAfterValue: {
    label: '调整后值',
    value: 'adjustAfterValue',
    asValue: 'adjustAfter',
    componentType: 'select-model',
    type: 'slot',
    code: 'depr_method_type',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
getFiscalPeriod()

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  })
})

function showFieldListItem(show, nameValue) {
  let fieldList = formInfo.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}

function openUseDeptWindow() {
  useDeptInfo.value.visible = true
  // 如果是编辑 且 带进来了 部门  去请求部门详情
  if (props.id && !useDeptInfo.value.checkedRowList.length) {
    let params = {
      idIn: selectAssetInfo.query.queryParams['useDeptIdMult'],
    }
    getDeptAll(params).then((res) => {
      if (res && res.success) {
        useDeptInfo.value.checkedRowList = res.data
      }
    })
  }
}
function openDepotWindow() {
  selectDepotInfo.value.visible = true
  if (props.id && !selectDepotInfo.value.checkedRowList.length) {
    let params = {
      idIn: selectAssetInfo.query.queryMap['depotId'].value,
    }
    getDeptAll(params).then((res) => {
      if (res && res.success) {
        selectDepotInfo.value.checkedRowList = res.data
      }
    })
  }
}
function selectUseDeptCallback(row) {
  tableInfo.data = []
  tableInfo.selections = []
  if (row && row.id) {
    let ids = row.id
    let name = row.name
    formInfo.data['useDeptId'] = ids.toString()
    formInfo.data['useDeptName'] = name.toString()
    useDeptInfo.value.checkedRowList = row
    selectAssetInfo.query.queryParams['useDeptIdMult'] = ids.toString()
    scanInfo.query.deptId = ids.toString()
  } else {
    formInfo.data['useDeptId'] = ''
    formInfo.data['useDeptName'] = ''
    useDeptInfo.value.checkedRowList = []
    selectAssetInfo.query.queryParams['useDeptIdMult'] = ''
    scanInfo.query.deptId = ''
  }
}
function selectDepotCallBack(row) {
  tableInfo.data = []
  tableInfo.selections = []
  if (row && row.id) {
    let ids = row.id
    let name = row.name
    formInfo.data['depotId'] = ids.toString()
    formInfo.data['depotName'] = name.toString()
    selectDepotInfo.value.checkedRowList = row
    selectAssetInfo.query.queryMap['depotId'].value = ids.toString()
    scanInfo.query.depotId = ids.toString()
  } else {
    formInfo.data['depotId'] = ''
    formInfo.data['depotName'] = ''
    selectDepotInfo.value.checkedRowList = []
    selectAssetInfo.query.queryMap['depotId'].value = ''
    scanInfo.query.depotId = ''
  }
}

function selectFinanceTypeInfoCallBack(row) {
  if (row) {
    clickRow.value['adjustAfter'] = row.id
    clickRow.value['adjustAfterValue'] = row.name
  } else {
    clickRow.value['adjustAfter'] = ''
    clickRow.value['adjustAfterValue'] = ''
  }
}
function openFinanceTypeWindow(row) {
  clickRow.value = row
  selectFinanceTypeInfo.query.idNotIn = row.adjustBefore
  selectFinanceTypeInfo.visible = true
}
function getFiscalPeriod() {
  getCurrentFiscalPeriod(2).then((res) => {
    if (res && res.success) {
      let index = formInfo.fieldList.findIndex(
        (item) => item.value === 'businessDate'
      )
      let fiscalPeriodName = res.data.name
      if (index > -1) {
        formInfo.fieldList[index].labelTip = `当前会计期间：${fiscalPeriodName}`
        formInfo.fieldList[index].TimePickerOptions = {
          disabledDate(time) {
            return (
              time.getTime() <
              new Date(res.data.startDate).getTime() - 24 * 60 * 60 * 1000
            )
          },
        }
      }
    }
  })
}
// flowData 外部流程页面调用
function saveAndSubmit(flowData) {
  save(true, flowData)
}
function save(isSaveAndSubmit, obj = {}) {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api = props.id
      ? updateAdjustFinanceType
      : isSaveAndSubmit === true
      ? createAdjustFinanceTypeAndSave
      : createAdjustFinanceType
    let assetName = tableInfo.data
      .filter((item) => item.adjustAfter === item.adjustBefore)
      .map((item) => item.assetName)
    if (assetName.length) {
      proxy.$alert(`资产【${assetName}】未作任何调整`, '操作提示', {
        confirmButtonText: '确定',
      })
      return
    }
    let param = {
      ...formInfo.data,
      adjustType: 13,
      details: tableInfo.data,
    }
    let flowParams = {}
    if (isSaveAndSubmit) {
      if (proxy.$route.query.processInstanceId) {
        api = flowSubmitAdjustFinanceTypeOrder
      }
      flowParams = {
        orderData: param,
        // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
        flowTaskCommentDto: { approvalType: 'submit' },
        processDefinitionKey: 'assetAdjustFinanceType',
        processInstanceId: obj.processInstanceId,
        taskId: obj.taskId,
      }
    }
    api(isSaveAndSubmit ? flowParams : param).then((res) => {
      if (res && res.success) {
        if (props.id && res.msgType === 'messageBox') {
          refushOrderDetail(props.id).then()
        }
        showDialog.value = false
        emits('returnModify', false)
      }
    })
  })
}
function onCallBackScanData(data, callback) {
  if (data && data.assetCode) {
    data.adjustBefore = data.financialClassifyType
    data.adjustBeforeValue = data.financialClassifyTypeValue
    data.assetId = data.id
    if (tableInfo.data) {
      tableInfo.data.forEach((item) => {
        item.isChoice = false
      })
      let index = tableInfo.data.findIndex(
        (item) => item.assetCode === data.assetCode
      )
      if (index !== -1) {
        callback(true)
      } else {
        tableInfo.data.unshift(data)
        callback(false)
      }
    } else {
      tableInfo.data.unshift(data)
      callback(true)
    }
  }
}
function addProduct() {
  if (tableInfo.data.length) {
    selectAssetInfo.query.queryMap.id.value = tableInfo.data
      .map((item) => item.assetId)
      .toString()
  } else {
    selectAssetInfo.query.queryMap.id.value = ''
  }
  selectAssetInfo.visible = true
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function removeProduct(selectRow = undefined) {
  if (selectRow) {
    tableInfo.data = tableInfo.data.filter((row) => row !== selectRow)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.data = tableInfo.data.filter(
          (row) => !tableInfo.selections.includes(row)
        )
      })
  }
}
function callBackAsset(data) {
  data.forEach((item) => {
    item.adjustBefore = item.financialClassifyType
    item.adjustBeforeValue = item.financialClassifyTypeValue
    item.assetId = item.id
  })
  tableInfo.data = data.concat(tableInfo.data)
}
function showAssetDetail(row) {
  assetDetailInfo.id = row.assetId
  assetDetailInfo.visible = true
}
function getMain() {
  getAdjustFinanceTypeById(props.id).then((res) => {
    if (res && res.success) {
      formInfo.data = res.data
      formInfo.data.position = Number(res.data.position) || 1
      selectAssetInfo.query.queryParams['useDeptIdMult'] = res.data.useDeptId
      selectAssetInfo.query.queryMap['depotId'].value = res.data.depotId
      scanInfo.query.deptId = res.data.useDeptId
      scanInfo.query.depotId = res.data.depotId
      proxy.$nextTick(() => {
        getList()
      })
    }
  })
}
function getList() {
  adjustFinanceTypeOrderDetailCustomizeListAll(filterInfo.query).then((res) => {
    if (res && res.success) {
      tableInfo.data = res.data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'assetAssetManageFinanceTypeAdjustModify-com.slip.spd.entity.vo.asset.AssetAdjustOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(tableInfo.fieldList, data.detail, true)
      tableInfo.fieldList = obj.fieldList
      proxy.$nextTick(() => {
        if (props.id) {
          getMain()
        }
      })
    }
  })
}
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  save,
  saveAndSubmit,
})
</script>
